import { OnChanges, SimpleChanges, Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, Validators, AbstractControl, ValidatorFn } from '@angular/forms';
@Directive({
  selector: '[phoneValidate]',
  providers: [{ provide: NG_VALIDATORS, useExisting: PhoneValidatorDirective, multi: true }]
})
export class PhoneValidatorDirective implements Validator, OnChanges {
  @Input() phoneValidate: string;
  private valFn = Validators.nullValidator;

  ngOnChanges(changes: SimpleChanges): void {
    const change = changes['phoneValidate'];
    if (change) {
      this.valFn = forbiddenNameValidator();
    } else {
      this.valFn = Validators.nullValidator;
    }
  }

  validate(control: AbstractControl): { [key: string]: any } {
    return this.valFn(control);
  }
}
// 不管国外了 有国际业务再改
export function forbiddenNameValidator(): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } => {
    const isPhone = /^([0-9]{3,4}-)?[0-9]{7,8}$/;
    const isMob = /^((\+?86)|(\(\+86\)))?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/;
    const result = isMob.test(control.value) || isPhone.test(control.value);
    return result ? null : { phoneValidator: result };
  };
}
